package com.example.cardgame

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.ByteArrayOutputStream

class EditActivity : AppCompatActivity() {
    private var avatarUri: Uri? = null
    private val REQUEST_IMAGE_CAPTURE = 1

    private lateinit var avatar_image: ImageView
    private lateinit var name_input: EditText
    private lateinit var student_id_input: EditText
    private lateinit var phone_input: EditText
    private lateinit var email_input: EditText
    private lateinit var gender_male: RadioButton
    private lateinit var gender_female: RadioButton
    private lateinit var hobbies_checkbox1: CheckBox
    private lateinit var hobbies_checkbox2: CheckBox
    private lateinit var hobbies_checkbox3: CheckBox

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_edit)
        // 视图初始化
        avatar_image = findViewById(R.id.avatar_image)
        name_input = findViewById(R.id.name_input)
        student_id_input = findViewById(R.id.student_id_input)
        phone_input = findViewById(R.id.phone_input)
        email_input = findViewById(R.id.email_input)
        gender_male = findViewById(R.id.gender_male)
        gender_female = findViewById(R.id.gender_female)
        hobbies_checkbox1 = findViewById(R.id.hobbies_checkbox1)
        hobbies_checkbox2 = findViewById(R.id.hobbies_checkbox2)
        hobbies_checkbox3 = findViewById(R.id.hobbies_checkbox3)
        val takePhotoButton = findViewById<Button>(R.id.button2)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        takePhotoButton.setOnClickListener {
            dispatchTakePictureIntent()
        }

        avatar_image.setOnClickListener { dispatchTakePictureIntent() }
    }


    @SuppressLint("QueryPermissionsNeeded")
    private fun dispatchTakePictureIntent() {
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//        Log.d("CameraIntent", "1")
        if (intent.resolveActivity(packageManager) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
//            Log.d("CameraIntent", "2")
        }
    }

    @Deprecated("This method has been deprecated in favor of using the Activity Result API\n      which brings increased type safety via an {@link ActivityResultContract} and the prebuilt\n      contracts for common intents available in\n      {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for\n      testing, and allow receiving results in separate, testable classes independent from your\n      activity. Use\n      {@link #registerForActivityResult(ActivityResultContract, ActivityResultCallback)}\n      with the appropriate {@link ActivityResultContract} and handling the result in the\n      {@link ActivityResultCallback#onActivityResult(Object) callback}.")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            val imageBitmap = data?.extras?.get("data") as Bitmap
            avatar_image.setImageBitmap(imageBitmap)

            // 将 Bitmap 转换为 Uri 保存
            val bytes = ByteArrayOutputStream()
            imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes)
            val path = MediaStore.Images.Media.insertImage(contentResolver, imageBitmap, "Avatar", null)
            avatarUri = Uri.parse(path) // 保存 Uri
        }
    }

    fun onSave(view: View) {
        val name = name_input.text.toString()
        val studentId = student_id_input.text.toString()
        val phone = phone_input.text.toString()
        val email = email_input.text.toString()
        val gender = when {
            gender_male.isChecked -> "男"
            gender_female.isChecked -> "女"
            else -> "未知"
        }
        val hobbies = mutableListOf<String>()
        if (hobbies_checkbox1.isChecked) hobbies.add("读书")
        if (hobbies_checkbox2.isChecked) hobbies.add("游泳")
        if (hobbies_checkbox3.isChecked) hobbies.add("运动")

        // 创建 Intent，并传递信息
        val intent = Intent(this, InfoActivity::class.java).apply {
            putExtra("name", name)
            putExtra("studentId", studentId)
            putExtra("phone", phone)
            putExtra("email", email)
            putExtra("gender", gender)
            putExtra("hobbies", hobbies.joinToString(","))

            putExtra("avatarUri", avatarUri.toString()) // 传递头像 URI
        }

        // 启动 InfoActivity
        startActivity(intent)
        finish()
    }

}